package com.sctvcloud.pingwu.ui.activities;

import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.videotracker.entity.VideoInfo;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.ShareFragment;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.pingwu.R;
import com.sctvcloud.pingwu.application.Cache;
import com.sctvcloud.pingwu.application.Constances;
import com.sctvcloud.pingwu.base.BaseCanPlayActivity;
import com.sctvcloud.pingwu.beans.FProgram;
import com.sctvcloud.pingwu.beans.LookBackDateBean;
import com.sctvcloud.pingwu.beans.LookBackNewsDate;
import com.sctvcloud.pingwu.http.AbsListNetCallback;
import com.sctvcloud.pingwu.http.AbsNetCallBack;
import com.sctvcloud.pingwu.http.NetUtils;
import com.sctvcloud.pingwu.ui.adapter.LookBackNewsDetailAdapter;
import com.sctvcloud.pingwu.ui.adapter.holder.LookBackNewsDetailHolder;
import com.sctvcloud.pingwu.ui.dialog.TimePopupDialog;
import com.sctvcloud.pingwu.ui.util.LookBackNewsDateComparator;
import com.sctvcloud.pingwu.ui.utils.GlideUtil;
import com.sctvcloud.pingwu.ui.utils.MutilDateLookBackGetHelper;
import com.sctvcloud.pingwu.ui.utils.SkipUtil;
import com.sctvcloud.pingwu.ui.utils.TitleUtils;
import com.sctvcloud.pingwu.ui.widget.BasePlayerView;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LookBackNewsDetailActivity extends BaseCanPlayActivity implements CanRefreshLayout.OnLoadMoreListener, LookBackNewsDetailAdapter.OnItemClickListener, TimePopupDialog.PopItemClick {

    @BindView(R.id.video_player)
    protected BasePlayerView videoPlayer;
    @BindView(R.id.column_name)
    protected CustomFontTextView columnName;
    @BindView(R.id.item_look_back_date)
    protected CustomFontTextView chooseDate;
    @BindView(R.id.item_play)
    protected View playerBg;
    @BindView(R.id.program_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView recyclerView;
//    @BindView(R.id.title_top_title)
//    protected CustomFontTextView title;


    private TimePopupDialog timePopupDialog;
    public static final String TIME_TAG = "dia_time_choice";
    public static final String COLUMN_ID = "lookback_column_id";
    public static final String COLUMN_NAME = "lookback_column_name";
    public static final String COLUMN_URL = "lookback_column_url";
    private Handler handler = new Handler();
    private List<LookBackNewsDate> programmeArray = new ArrayList<>();
    private LookBackNewsDetailAdapter adapter;
    private MutilDateLookBackGetHelper getHelper;
    private String columnNameTxt = "";
    private String columnID = "";
    private String dataUrl;
    private FProgram showingProgram;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        refreshLayout.setOnLoadMoreListener(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        columnNameTxt = getIntent().getStringExtra(COLUMN_ID);
        columnNameTxt = getIntent().getStringExtra(COLUMN_NAME);
        dataUrl = getIntent().getStringExtra(COLUMN_URL);
        columnName.setText(columnNameTxt);
        videoPlayer.setMute(false);
        adapter = new LookBackNewsDetailAdapter(this, null, this);
        recyclerView.setAdapter(adapter);
        SkipUtil.skipToAddUserOperate(this, getOwnerName(), 9, 7, "回看栏目", columnID, Cache.getInstance().getCurrentChannelId());
        getLookBackDate();
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_lookback_detail);
        ButterKnife.bind(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
        }

    }

    @Override
    public void onLoadMore() {
        getLookBackNews(false);
    }

    private MutilDateLookBackGetHelper initDateHelper() {
        if (getHelper == null) {
            getHelper = new MutilDateLookBackGetHelper(this);
            getHelper.setShouldSetTitleAfter(true);
        }
        return getHelper;
    }


    @Override
    public void onNetPromptCallBacked(boolean isContinue) {
        super.onNetPromptCallBacked(isContinue);
        videoPlayer.startPlay();
    }


    /**
     * 获取回看栏目的节目日期列表
     */
    private void getLookBackDate() {
        NetUtils.getNetAdapter().getLookBackNewsDateObj(getOwnerName(), dataUrl, new AbsNetCallBack<LookBackDateBean>(LookBackDateBean.class) {

            @Override
            public void onSuc(LookBackDateBean bean) {
                JLog.e("number ", "--------getLookBackDate bean=" + bean);
                List<LookBackNewsDate> list = bean.getProgrammeArray();
                if (ListUtils.isListValued(list)) {
                    for (int i = 0; i < list.size(); i++) {
                        list.get(i).setProgrammeListUrl( list.get(i).getProgrammeListUrl());
                    }
                    programmeArray.clear();
                    programmeArray.addAll(list);
                    initDateHelper().setDates(programmeArray);
                    getLookBackNews(true);
                }
            }

            @Override
            public LookBackDateBean doInBackground(LookBackDateBean newsDates) {
                LogUtil.e("LOOKBACK doInBackground  = " + newsDates);
                List<LookBackNewsDate> programmeArray = newsDates.getProgrammeArray();
                if (ListUtils.isListValued(programmeArray)) {
                    LookBackNewsDate stick = null;
                    if (programmeArray.get(0).getProgrammeDate().equalsIgnoreCase("isStick")) {
                        stick = programmeArray.get(0);
                        programmeArray.remove(0);
                    }
                    if (programmeArray.size() > 2) {
                        Collections.sort(programmeArray, new LookBackNewsDateComparator());
                    }
                    if (null != stick) {
                        programmeArray.add(0, stick);
                    }
                }
                return super.doInBackground(newsDates);
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                refreshLayout.loadMoreComplete();
            }

            @Override
            public void onEnd() {
                super.onEnd();
//                onNetFinish(newKey);
            }
        });
    }

    private void getLookBackNews(final boolean reset) {

        if (!initDateHelper().hasValuedDate()) {
            return;
        }

//        isReset = reset;
        getHelper.getNewsList(10, reset
                , new AbsListNetCallback<FProgram>(FProgram.class) {

                    @Override
                    public void onSuc(List<FProgram> list) {
                        if (ListUtils.isListValued(list)) {
                            if (reset) {
                                adapter.setData(list);
                                initPlayData(list.get(0), true);
                                recyclerView.smoothScrollToPosition(0);
                            } else {
                                adapter.addData(list);
                            }
                        } else {
                            if (reset) {
                                toast("未请求的相关数据");
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
//                        if (reset) {
//                            toast("为请求的相关数据");
//                        }
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        int count = adapter.getItemCount();
                        if (count == 0) {
                            toast("未请求的相关数据");
                        }
                        refreshLayout.loadMoreComplete();
                    }
                });
    }

    /**
     * 弹出日期选择框
     */
    private void showDateDialog() {
        if (timePopupDialog == null) {
            timePopupDialog = new TimePopupDialog().setPopItemClick(this);
        }
        safeShowDialog(timePopupDialog, TIME_TAG);
    }

    @Override
    public void selectTime(String year, String month, String day) {
        LogUtil.e("selectTime year= " + year + "  month = " + month + "  day = " + day);
        List<LookBackNewsDate> dateList = getProgrammeArray(year + "-" + month + "-" + day);
        initDateHelper().setDates(dateList);
        getLookBackNews(true);
    }


    private List<LookBackNewsDate> getProgrammeArray(String date) {
        List<LookBackNewsDate> dateArray = new ArrayList<>();
        boolean isAdd = false;
        for (int i = 0; i < programmeArray.size(); i++) {
            if (2 == DateUtils.compareDate(date, programmeArray.get(i).getProgrammeDate())) {
                isAdd = true;
            }
            if (isAdd) {
                LogUtil.e("selectTime date= " + programmeArray.get(i).getDateString());
                dateArray.add(programmeArray.get(i));
            }
        }
        return dateArray;
    }

    private LookBackNewsDetailHolder lastViewHolder;
    private int lastIndex = 0;

    @Override
    public void OnItemClick(LookBackNewsDetailHolder viewHolder, FProgram item, int position) {
        if (lastIndex != position) {
            if (null == lastViewHolder) {
                RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
                View lastView = manager.findViewByPosition(lastIndex);
                if (null != lastView && recyclerView.getChildViewHolder(lastView) instanceof LookBackNewsDetailHolder) {
                    lastViewHolder = (LookBackNewsDetailHolder) recyclerView.getChildViewHolder(lastView);
                }
            }
            adapter.updateHolderStatus(lastViewHolder, viewHolder);
            adapter.updateDataStatus(lastIndex, position);
            lastIndex = position;
            lastViewHolder = viewHolder;
            //回看新闻点击
            initPlayData(item, true);
        }
    }

    /**
     * 初始化播放数据
     *
     * @param item
     */
    private void initPlayData(final FProgram item, final boolean isPlayNow) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                showingProgram = item;
                if (videoPlayer.getThumbImge() != null) {
                    GlideUtil.getGlideWithLarge169DefNotFit(LookBackNewsDetailActivity.this, item.getProgrammeImage()).into(videoPlayer.getThumbImge());
                }

                videoPlayer.setUp(item.getProgrammeUrl(), false, item.getProgrammeTitle());
                if (isPlayNow) {
                    videoPlayer.startPlay();
                    SkipUtil.skipToAddUserOperate(LookBackNewsDetailActivity.this, getOwnerName(), 9, 7, "节目回看", item.getProgrammeId(), Cache.getInstance().getCurrentChannelId());
                }
                initPlayer(videoPlayer, item);
                playerBg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        playerBg.setVisibility(View.GONE);
                        videoPlayer.startPlay();
                        SkipUtil.skipToAddUserOperate(LookBackNewsDetailActivity.this, getOwnerName(), 9, 7, "节目回看", item.getProgrammeId(), Cache.getInstance().getCurrentChannelId());
                    }
                });
            }
        }, 200);
    }

    /**
     * 初始化播放控件，以实现全屏等功能
     *
     * @param player
     */
    private void initPlayer(BasePlayerView player, FProgram item) {
        VideoInfo videoInfo = new VideoInfo("");
        videoInfo.Cdn = "cdn";
        videoInfo.VideoOriginalName = item.getProgrammeName();
        videoInfo.VideoName = item.getProgrammeName();
        videoInfo.VideoUrl = Constances.ST_BASE_URL + item.getProgrammeUrl();
        videoInfo.extendProperty1 = "直播三台APP_Android";
        videoInfo.extendProperty1 = "";
        videoInfo.extendProperty1 = NetUtils.GetNetName(this);
        videoInfo.setVideoWebChannel("///");
        if (null != player) {
//            initVideoPlayer(player, videoInfo, videoInfo.VideoUrl.endsWith("m3u8"));
            initVideoPlayer(player, videoInfo, videoInfo.VideoUrl.endsWith("m3u8"), new OnPlayerFullClickListener() {
                @Override
                public void onFullClick(boolean isNormal) {
                    isNormalScreenShow = isNormal;
                }
            });
        }
    }

    @OnClick(value = {R.id.title_top_layout_back, R.id.title_top_layout_edit, R.id.item_look_back_date})
    public void topClick(View view) {
        switch (view.getId()) {
            case R.id.title_top_layout_back:
                finish();
                break;
            case R.id.title_top_layout_edit:
                if (showingProgram != null && !TextUtils.isEmpty(showingProgram.getSharedUrl())) {
                    this.setNewsId(showingProgram.getProgrammeId());
                    showShareFragment(showingProgram, new ShareFragment.OnShareFragmentClickListener() {
                        @Override
                        public void onClick(Pair<String, String> pairs) {

                        }
                    });
                } else {
                    toast(R.string.share_data_wrong);
                }
                break;
            case R.id.item_look_back_date:
                showDateDialog();
                break;
        }
    }

    private boolean isNormalScreenShow = true;

    @Override
    public void onBackPressed() {
        if (isNormalScreenShow) {
//            isCanPlayVideo = false;

            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (null != videoPlayer) {
                        videoPlayer.release();
                    }
                    LookBackNewsDetailActivity.super.onBackPressed();
                }
            }, 200);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        if (null != videoPlayer) {
            videoPlayer.onVideoPause();
            videoPlayer.release();
        }
        super.onDestroy();
    }
}

